<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>用户分表管理</span>
          <el-button type="primary" plain @click="goBackToUser">返回用户管理</el-button>
        </div>
      </template>
      <div class="card-content">
        <!-- 状态信息 -->
        <el-alert
          title="分表状态"
          type="info"
          :closable="false"
          :description="isShardingEnabled ? '当前已启用ShardingSphere分表功能' : '当前已禁用ShardingSphere分表功能'"
          show-icon
        />
        
        <el-alert
          v-if="tableStatus"
          style="margin-top: 20px"
          :title="tableStatus.success ? '分表创建状态' : '分表创建警告'"
          :type="tableStatus.success ? 'success' : 'warning'"
          :closable="false"
          :description="tableStatus.message"
          show-icon
        />

        <el-row :gutter="24" style="margin-top: 20px">
          <el-col :span="10">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <span>分表启用控制</span>
                </div>
              </template>
              <div>
                <el-switch
                  v-model="isShardingEnabled"
                  :active-text="isShardingEnabled ? '已启用' : '未启用'"
                  :inactive-text="isShardingEnabled ? '已启用' : '未启用'"
                  @change="handleShardingChange"
                />
                <div style="margin-top: 10px">
                  <p>启用后，用户数据将在多个分片表中存储，提高查询性能</p>
                  <p>注意：请先确认已完成数据迁移后再启用分表功能</p>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="14">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <span>数据统计</span>
                </div>
              </template>
              <div>
                <div v-if="isLoading">
                  <el-skeleton :rows="3" animated />
                </div>
                <div v-else>
                  <el-descriptions border>
                    <el-descriptions-item label="分片表记录总数">{{ stats.shardingCount || 0 }}</el-descriptions-item>
                    <el-descriptions-item label="分表状态">{{ tableStatus?.success ? '已创建' : '未创建' }}</el-descriptions-item>
                    <el-descriptions-item label="最近迁移记录数">{{ migrationResult?.migratedCount || 0 }}</el-descriptions-item>
                  </el-descriptions>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 迁移工具 -->
        <el-card shadow="hover" style="margin-top: 20px">
          <template #header>
            <div class="card-header">
              <span>数据迁移工具</span>
            </div>
          </template>
          
          <div>
            <el-steps :active="migrationStep" finish-status="success" style="margin-bottom: 20px">
              <el-step title="检查分表" description="检查分表是否已创建"></el-step>
              <el-step title="数据迁移" description="将原表数据迁移至分表"></el-step>
              <el-step title="验证数据" description="验证迁移是否成功"></el-step>
              <el-step title="完成" description="启用分表功能"></el-step>
            </el-steps>
            
            <div style="text-align: center; margin: 20px 0">
              <el-button 
                type="primary" 
                @click="checkTables" 
                :disabled="migrationStep > 0 || isLoading"
              >
                1. 检查分表
              </el-button>
              
              <el-button 
                type="primary" 
                @click="startMigration" 
                :disabled="migrationStep !== 1 || isLoading || !tableStatus?.success"
              >
                2. 开始迁移
              </el-button>
              
              <el-button 
                type="primary" 
                @click="validateMigration" 
                :disabled="migrationStep !== 2 || isLoading"
              >
                3. 验证数据
              </el-button>
              
              <el-button 
                type="success" 
                @click="enableSharding" 
                :disabled="migrationStep !== 3 || isLoading || isShardingEnabled"
              >
                4. 启用分表
              </el-button>
            </div>
            
            <el-alert
              v-if="migrationMessage"
              :title="migrationTitle || '迁移信息'"
              :type="migrationStatus"
              :closable="false"
              :description="migrationMessage"
              show-icon
              style="margin-bottom: 20px"
            />

            <div v-if="migrationStep === 1 && tableStatus?.success">
              <el-form label-width="120px">
                <el-form-item label="批次大小">
                  <el-input-number v-model="batchSize" :min="100" :max="10000" :step="100" />
                  <span style="margin-left: 10px; color: #999">每批处理的记录数，较小的值可减少内存占用</span>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-card>

        <!-- 简单测试操作 -->
        <el-card shadow="hover" style="margin-top: 20px">
          <template #header>
            <div class="card-header">
              <span>分表测试</span>
            </div>
          </template>
          
          <el-row :gutter="24">
            <el-col :span="24">
              <div style="margin-bottom: 20px">
                <el-alert
                  title="通过分表查询用户数据"
                  type="info"
                  description="以下是通过ShardingSphere-JDBC分表查询到的用户数据"
                  :closable="false"
                  show-icon
                />
              </div>
              
              <el-table :data="userList" style="width: 100%">
                <el-table-column prop="id" label="ID" width="180" />
                <el-table-column prop="username" label="用户名" width="180" />
                <el-table-column prop="email" label="邮箱" />
                <el-table-column prop="mobilePhone" label="手机号" />
                <el-table-column prop="status" label="状态">
                  <template #default="scope">
                    {{ scope.row.status === 1 ? '启用' : '禁用' }}
                  </template>
                </el-table-column>
              </el-table>
              
              <div style="margin-top: 20px; text-align: center">
                <el-pagination
                  :current-page="currentPage"
                  :page-size="pageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script>
import { 
  listShardingUser, 
  getShardingStatus, 
  setShardingEnable, 
  checkShardingTables, 
  getShardingStats, 
  migrateData, 
  validateMigration as validateShardingMigration 
} from "@/api/user";

export default {
  name: 'UserSharding',
  data() {
    return {
      isShardingEnabled: false,
      isLoading: false,
      tableStatus: null,
      stats: {},
      migrationStep: 0,
      migrationMessage: '',
      migrationTitle: '',
      migrationStatus: 'info',
      migrationResult: null,
      batchSize: 1000,
      
      // 用户列表数据
      userList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
    }
  },
  created() {
    this.getShardingStatusInfo();
    this.getShardingStats();
    this.loadUserList();
  },
  methods: {
    // 获取分表启用状态
    async getShardingStatusInfo() {
      try {
        const res = await getShardingStatus();
        if (res.code === 200) {
          this.isShardingEnabled = res.data.enabled;
        }
      } catch (error) {
        this.$message.error('获取分表状态失败');
      }
    },
    
    // 获取分表统计信息
    async getShardingStats() {
      this.isLoading = true;
      try {
        const res = await getShardingStats();
        if (res.code === 200) {
          this.stats = res.data;
        }
      } catch (error) {
        this.$message.error('获取分表统计信息失败');
      } finally {
        this.isLoading = false;
      }
    },
    
    // 处理分表启用状态变更
    async handleShardingChange(value) {
      try {
        const res = await setShardingEnable(value);
        if (res.code === 200) {
          this.$message.success(res.msg || '设置成功');
        } else {
          this.isShardingEnabled = !value; // 恢复状态
          this.$message.error(res.msg || '设置失败');
        }
      } catch (error) {
        this.isShardingEnabled = !value; // 恢复状态
        this.$message.error('设置失败');
      }
    },
    
    // 检查分表是否已创建
    async checkTables() {
      this.isLoading = true;
      this.migrationMessage = '正在检查分表是否创建...';
      this.migrationStatus = 'info';
      this.migrationTitle = '检查中';
      
      try {
        const res = await checkShardingTables();
        if (res.code === 200) {
          this.tableStatus = {
            success: true,
            message: res.msg
          };
          this.migrationStep = 1;
          this.migrationMessage = res.msg;
          this.migrationStatus = 'success';
          this.migrationTitle = '检查完成';
        } else {
          this.tableStatus = {
            success: false,
            message: res.msg
          };
          this.migrationMessage = res.msg;
          this.migrationStatus = 'warning';
          this.migrationTitle = '检查警告';
        }
      } catch (error) {
        this.tableStatus = {
          success: false,
          message: '检查分表失败，请确保数据库中已创建分表'
        };
        this.migrationMessage = '检查分表失败，请确保数据库中已创建分表';
        this.migrationStatus = 'error';
        this.migrationTitle = '检查失败';
      } finally {
        this.isLoading = false;
      }
    },
    
    // 开始数据迁移
    async startMigration() {
      this.isLoading = true;
      this.migrationMessage = '数据迁移中，请稍候...';
      this.migrationStatus = 'info';
      this.migrationTitle = '迁移中';
      
      try {
        const res = await migrateData(this.batchSize);
        if (res.code === 200) {
          this.migrationResult = res.data;
          this.migrationStep = 2;
          this.migrationMessage = `成功迁移 ${res.data.migratedCount} 条记录`;
          this.migrationStatus = 'success';
          this.migrationTitle = '迁移完成';
          
          // 刷新统计数据
          this.getShardingStats();
        } else {
          this.migrationMessage = res.msg || '迁移失败';
          this.migrationStatus = 'error';
          this.migrationTitle = '迁移失败';
        }
      } catch (error) {
        this.migrationMessage = '数据迁移过程中出现错误，请查看系统日志';
        this.migrationStatus = 'error';
        this.migrationTitle = '迁移失败';
      } finally {
        this.isLoading = false;
      }
    },
    
    // 验证迁移数据
    async validateMigration() {
      this.isLoading = true;
      this.migrationMessage = '正在验证数据一致性...';
      this.migrationStatus = 'info';
      this.migrationTitle = '验证中';
      
      try {
        const res = await validateShardingMigration();
        if (res.code === 200) {
          this.migrationStep = 3;
          this.migrationMessage = res.msg;
          this.migrationStatus = 'success';
          this.migrationTitle = '验证完成';
        } else {
          this.migrationMessage = res.msg || '验证失败';
          this.migrationStatus = 'error';
          this.migrationTitle = '验证失败';
        }
      } catch (error) {
        this.migrationMessage = '数据验证过程中出现错误';
        this.migrationStatus = 'error';
        this.migrationTitle = '验证失败';
      } finally {
        this.isLoading = false;
      }
    },
    
    // 启用分表
    async enableSharding() {
      try {
        const res = await setShardingEnable(true);
        if (res.code === 200) {
          this.isShardingEnabled = true;
          this.migrationStep = 4;
          this.migrationMessage = '分表功能已成功启用';
          this.migrationStatus = 'success';
          this.migrationTitle = '完成';
          this.$message.success('分表功能已启用');
        } else {
          this.$message.error(res.msg || '启用失败');
        }
      } catch (error) {
        this.$message.error('启用分表失败');
      }
    },
    
    // 加载分表用户列表
    loadUserList() {
      this.isLoading = true;
      listShardingUser({
        pageNum: this.currentPage,
        pageSize: this.pageSize
      })
        .then(res => {
          if (res.code === 200) {
            this.userList = res.data.records;
            this.total = res.data.total;
          } else {
            this.$message.error(res.msg || '获取用户列表失败');
          }
        })
        .catch(() => {
          this.$message.error('获取用户列表失败');
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    
    // 处理分页大小变更
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadUserList();
    },
    
    // 处理页码变更
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadUserList();
    },
    
    // 返回用户管理页面
    goBackToUser() {
      this.$router.push({ path: '/user' });
    }
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  margin-top: 16px;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}

.el-steps {
  margin-bottom: 30px;
}
</style> 